package com.giw.uima.makers;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.apache.uima.TokenAnnotation;
import org.apache.uima.UIMAFramework;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.FSIterator;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.resource.ResourceSpecifier;
import org.apache.uima.util.XMLInputSource;

import com.giw.uima.ts.CompetitionAnnotation;
import com.giw.uima.ts.TeamAnnotation;


public class SurnameIdentifier {

	private static final String DICT_SURNAME_PATH=
		"src/main/resources/dictionaries/dictionary_surname.txt";

	public List<String> find_surname(String text,List<String> surnameList,List<String> namList,
			List<String> teams,List<String> competitions) throws AnalysisEngineProcessException, 
	ResourceInitializationException{
		JCas jcas=this.runTeamCompetitionAnnotator(text);
		FSIterator<Annotation> iterator=jcas.getAnnotationIndex(TokenAnnotation.type).iterator();
		Annotation previous;
		Annotation next=null;
		previous=iterator.get();
		iterator.moveToNext();
		while(iterator.hasNext()){
			next=iterator.get();
			if(this.isUp(previous)&&!this.is_already_annotation(jcas, previous)&&
					isUp(next)&&
					Collections.binarySearch(namList, previous.getCoveredText())>=0
					&&Collections.binarySearch(surnameList, next.getCoveredText())<0
					&&Collections.binarySearch(teams, next.getCoveredText())<0
					&&Collections.binarySearch(competitions, previous.getCoveredText())<0
					){
				surnameList.add(next.getCoveredText());
				Collections.sort(surnameList);
				this.addSurnameToDictionary(next.getCoveredText());
			}
			previous=next;
			iterator.moveToNext();
		}
		return surnameList;
	}



	private boolean is_already_annotation(JCas jcas,Annotation annotation){

		int begin = annotation.getBegin();
		int end = annotation.getEnd();
		FSIterator<Annotation> it_team = jcas.getAnnotationIndex(TeamAnnotation.type).iterator();
		FSIterator<Annotation> it_competition = jcas.getAnnotationIndex(CompetitionAnnotation.type).iterator();
		Annotation a_team;
		Annotation a_comp;

		while (it_team.hasNext()) {
			a_team = it_team.get();
			if ((a_team.getBegin()>=begin)&&(a_team.getEnd()<=end))
				return true;
			it_team.moveToNext();
		}
		while (it_competition.hasNext()) {
			a_comp = it_competition.get();
			if ((a_comp.getBegin()>=begin)&&(a_comp.getEnd()<=end))
				return true;
			it_competition.moveToNext();
		}
		return false;
	}


	private JCas runTeamCompetitionAnnotator(String text) throws 
	ResourceInitializationException, AnalysisEngineProcessException{
		JCas jcas=null;
		AnalysisEngine engine=null;
		try{
			// create a UIMA XML resource
			XMLInputSource in = new XMLInputSource("src/main/resources/AggregateTeamCompetition.xml");
			// parse the XML to access the resource defined properties
			ResourceSpecifier specifier = UIMAFramework.getXMLParser().parseResourceSpecifier(in);
			// create Analysis Engine from the ResourceSpecifier
			engine = UIMAFramework.produceAnalysisEngine(specifier);

			jcas=engine.newJCas();
		}
		catch(Exception e){
			throw new ResourceInitializationException(e);
		}


		try {
			// set the text to be analyzed inside the JCas
			jcas.setDocumentText(text);
			// force document language to "x-unspecified" (usually this is extracted)
			jcas.setDocumentLanguage("x-unspecified");
			// run the analysis engine on the JCas
			engine.process(jcas);
			engine=null;

		} catch (Exception e) {
			throw new AnalysisEngineProcessException(e);
		}
		return jcas;
	}


	private boolean isUp(Annotation annotation) {
		String text=annotation.getCoveredText();
		Character c=text.charAt(0);
		return Character.isUpperCase(c);
	}

	private void addSurnameToDictionary(String surname){
		try{
			System.out.println(surname);
			File f = new File(DICT_SURNAME_PATH);
			FileOutputStream fos=new FileOutputStream(f,true);
			PrintStream ps=new PrintStream(fos);
			ps.println(surname);
			fos.close();
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}


	public static void main(String[] args) throws AnalysisEngineProcessException, 
	ResourceInitializationException{
		SurnameIdentifier si=new SurnameIdentifier();
		List<String> ls=new LinkedList<String>();
		ls.add("Giorgio");
		ls.add("Marco");
		List<String> ld=new LinkedList<String>();
		ld=si.find_surname("Marco Giovanni aaaa, Giorgio Totti cccc cccc ", ld, ls, ld, ld);
		for(String s:ld){
			System.out.println(s);
		}
	}

}
